package com.star.starrpc.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * packageName com.star.starrpc.serializer
 *
 * @author zerostart
 * @className JdkSerializer
 * @date 2024/11/17
 * @description
 */
public class JdkSerializer implements Serializer {


    @Override
    public <T> byte[] serialize(T object) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

        objectOutputStream.writeObject(object);
        objectOutputStream.close();

        return outputStream.toByteArray();
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) throws Exception {

        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

        try {
            return (T) objectInputStream.readObject();
        } catch (Exception e) {
            throw new Exception("反序列化失败", e);
        } finally {
            objectInputStream.close();
        }
    }
}
